<template>
    <div class="routerContent nearbyStoreContainer">
        <nav>附近门店</nav>
        <div class="noAddressList" v-if="noAddressListShow">抱歉,未找到相关餐厅</div>
        <div class="inpsearch">
            <div class="city" @click="chooseCity(cityName)">{{ cityName | cityNameFilter4 }} <span>▼</span></div>
            <div class="inp_in">
                <span></span>
                <x-input v-model="nearbyStoreName" :debounce="500" @on-change="nearbyStoreNameChange"
                         placeholder="请输入搜索关键字" @on-blur="nearbyStoreNameBlur" @on-focus="nearbyStoreNameFocus">
                    <!--<img slot="label" style="padding-right:10px;display:block;" src="http://dn-placeholder.qbox.me/110x110/FF2D55/000" width="24" height="24">-->
                </x-input>
            </div>
        </div>
        <scroller lock-x ref="scroller" scrollbar-y use-pullup :pullup-config="pullupConfig"
                  @on-pullup-loading="addressListLoadMore" v-model="addressListStatus" :height="-105+'px'">
            <div class="addresslist" v-if="addressList">
                <div class="addresslistLi" v-for="item in addressList" @click="doXStore(item)">
                    <p v-html="item.stStoreName" class="addresslistName"></p>
                    <p v-html="item.cityAddress"></p>
                    <span class="unit">{{ item.distance }} {{ item.unit }}</span>
                </div>
            </div>
        </scroller>

    </div>
</template>
<script>
    import {XHeader, Scroller, XInput} from 'vux'

    import {nearStoreService, isFirstInService, isBindingService} from '../services'

    import {mapState, mapActions} from 'vuex'

    export default {
        components: {
            XHeader,
            Scroller,
            XInput
        },
        beforeRouteEnter (to, from, next){   
            
            /**
              * John modify
              */
            // const stStoreId = window.localStorage.getItem('stStoreId') || '';
            // isBindingService().save().then(res => {
            //     const info = res.data.code;
            //     //如果还没有注册
            //     if(info == 400){
            //         next({
            //             path : "/phoneValida",
            //         });                  
            //     }else{
            //         //stStoreId已经存在，表明已经进入过某家店
            //         if(stStoreId){
            //             next({
            //                 path : "/setTakeTime",
            //                 query : {
            //                    stStoreId : stStoreId 
            //                 }
            //             }); 
            //         }else{
            //             next();
            //         }
            //     }
            // }).catch(error=>{
            //     console.log("123:" + JSON.stringify(error))
            //     next();
            // })
            next();
        },
        beforeCreate(){
            
            //            if (this.$route.name == 'historyOrder') {
            //                if (stStoreId) {
            //                    this.$router.push({
            //                        name: 'setTakeTime',
            //                        query: {
            //                            path:this.$route.name
            //                        }
            //                    })
            //                }else{
            //                    isFirstInService().save().then((res) => {
            //                       const info = res.data.data;
            //                        if(info.storeId){
            //                            window.localStorage.setItem('stStoreId',info.storeId);
            //                        }
            //                        this.getWeiXinLocation('广州');
            //                    })
            //                }
            //            }else{

            //            if(true){
            //                this.$router.push({
            //                    name: 'phoneValida',
            //                    query: {}
            //                })
            //                return
            //            }

            // const stStoreId = window.localStorage.getItem('stStoreId');
            // isBindingService().save().then((res) => {
            //     const info = res.data.code;
            //     if(info == 400){
            //         this.$router.replace({
            //             name: 'phoneValida',
            //             query: {}
            //         })
            //     }else {
            //         if (stStoreId) {
            //             this.$router.replace({
            //                 name: 'setTakeTime',
            //                 query: {
            //                     stStoreId: stStoreId
            //                 }
            //             })
            //         }
            //     }
            // })
        },
        mounted () {
        },
        computed: {
            ...mapState({               
                switchCityObj: state => state.switchCity.switchCityObj,
                nearStoreObj: state => state.switchCity.nearStoreObj,
            })
        },
        data(){
            return {
                pageNo: 0,
                addressList: [],
                cityName: '',
                nearbyStoreName: '',
                noAddressListShow: false,
                /*上拉加载配置*/
                pullupConfig: {
                    content: '',
                    downContent: '松开进行加载',
                    upContent: '上拉加载更多',
                    loadingContent: '加载中...'
                },
                addressListStatus: {
                    pullupStatus: 'default'
                },
            }
        },
        watch: {
            deep: true,
            immediate: true,
            switchCityObj(val, oldVal){
                this.cityName = val.cityName;
                this.pageNo = 0;
                this.addressList = [];
                this.getWeiXinLocation(val.cityName);
            },
            nearStoreObj(){
                this.pageNo = 0;
                this.addressList = [];
                this.cityName = this.nearStoreObj ? this.nearStoreObj.cityName : '';
                this.getWeiXinLocation()
            }
        },
        created(){
            this.pageNo = 0;
            this.addressList = [];
            this.nearbyStoreName = '';
            this.getWeiXinLocation(this.cityName)
        },
        activated(){
            this.pageNo = 0;
            this.addressList = [];
            this.nearbyStoreName = '';
            this.getWeiXinLocation(this.cityName)
        },
        deactivated(){

        },
        methods: {
            ...mapActions([
                'updateStoreId',
                'updateNearStoreObj'
            ]),
            getWeiXinLocationF(){
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: (res) => {
                        let latitude = res.latitude;//纬度
                        let longitude = res.longitude;//经度

                        const map = new BMap.Map("allmap")
                        const myGeo = new BMap.Geocoder();
                        const geolocation = new BMap.Geolocation()
                        const pt = new BMap.Point(res.longitude, res.latitude)

                        myGeo.getLocation(pt, (rs) => {
                            const addComp = rs.addressComponents;
                            const detailInfo = addComp.province + "" + addComp.city + "" + addComp.district + "" + addComp.street + "" + addComp.streetNumber;
                            const city = addComp.city.substring(0, addComp.city.length - 1);
                            const nearStore = {
                                cityName: city,
                                longitude: longitude,
                                latitude: latitude,
                            }
                            this.updateNearStoreObj(nearStore);
                        })
                    }
                });
            },
            getWeiXinLocation(val, keyword){
                this.cityName = val || this.nearStoreObj.cityName;
                const nearStore = {
                    cityName: this.cityName,
                    longitude: this.nearStoreObj.longitude,
                    latitude: this.nearStoreObj.latitude,
                }
                if (keyword) {
                    nearStore.keyword = keyword;
                }
                if (this.cityName) {
                    this.getNearStore(nearStore);
                }
            },
            getNearStore(nearStore){
                nearStore.pageNo = ++this.pageNo;
                nearStoreService().save(nearStore).then((res) => {
                    const body = res.body;
                    if (body && body.code == 200) {
                        if (body.pageNo > 1) {
                            this.addressList = this.addressList.concat(body.data);
                        } else {
                            this.addressList = body.data;
                        }
                        if (this.addressList && this.addressList.length == 0) {
                            this.noAddressListShow = true;
                        } else {
                            this.noAddressListShow = false;
                            if (body.lastPage) {
                                this.addressListStatus.pullupStatus = 'disabled';
                            } else {
                                this.addressListStatus.pullupStatus = 'enabled';
                            }
                        }
                    } else {
                        this.noAddressListShow = true;
                        this.addressListStatus.pullupStatus = 'enabled';
                    }
                    setTimeout(() => {
                        this.$refs.scroller.reset()
                    }, 500)
                }).catch((error)=>{
                    console.log(error)
                })
            },
            chooseCity(cityName){
                if (cityName) {
                    console.log("cityName : " + cityName);
                    this.$router.push({
                        name: 'switchCity',
                        query: {
                            cityName: cityName,
                        }
                    })
                }
            },
            nearbyStoreNameChange(value){
                this.pageNo = 0;
                this.addressList = [];
                this.getWeiXinLocation(this.cityName, value);
            },
            nearbyStoreNameBlur(){

            },
            nearbyStoreNameFocus(){

            },
            doXStore(item){
                this.updateStoreId(item.stStoreId);
                window.localStorage.setItem('stStoreId', item.stStoreId);
                if (item.stStoreId) {
                    this.$router.push({
                        name: 'setTakeTime',
                        query: {}
                    })
                }
            },
            addressListLoadMore(){
                this.getWeiXinLocation();
                setTimeout(() => {
                    this.$refs.scroller.donePullup()
                }, 10)
            }
        },
        updated(){
            setTimeout(() => {
                this.$refs.scroller.reset()
            }, 1000)
        }
    }
</script>
<style lang="less" rel="stylesheet/less">
    .nearbyStoreContainer {
        background-color: #fff;
        font-size: 0.8rem;
        position: relative;

        nav {
            font-size: .75rem;
            color: #fff;
            width: 100%;
            height: 2rem;
            line-height: 2rem;
            background: #fc8672;
            text-align: center;
        }
        .inpsearch {
            padding: 0.5rem;
            border-bottom: 1px solid #dfdfdf;
            display: -webkit-flex;
            display: flex;
            .city {
                border-radius: 5px;
                border: 1px solid #dfdfdf;
                padding: 0.4rem 0.6rem 0.4rem 1rem;
                span {
                    color: #999;
                }
            }
            .inp_in {
                border-radius: 5px;
                border: 1px solid #dfdfdf;
                margin-left: 1rem;
                position: relative;
                width: 60%;
                span {
                    position: absolute;
                    left: 0;
                    display: inline-block;
                    width: 15%;
                    height: 100%;
                    background: url(../assets/img/u214.png) no-repeat center right;
                    background-size: 60%;
                }
                input {
                    height: 100%;
                    display: inline-block;
                    border: none;
                    width: 85%;
                    margin-left: 10%;
                    padding-left: 1rem;
                    background-color: #fbf9fe;
                    border-radius: 5px;
                }

            }
        }
        .addresslist {
            .addresslistLi {
                position: relative;
                width: 100%;
                padding: 0.5rem 16% 0.5rem 14%;
                background: url(../assets/img/u201.png) no-repeat 5% center;
                background-size: 5%;
                border-bottom: 1px solid #dfdfdf;
                font-size: 0.8rem;
                p:nth-child(2) {
                    font-size: 0.6rem;
                    color: #999;
                    margin-top: .25rem;
                }
                .addresslistName {
                    width: 80%;
                }
                .unit {
                    position: absolute;
                    top: 50%;
                    transform: translateY(-90%);
                    -webkit-transform: translateY(-90%);
                    right: 3%;
                }
            }
        }
        .noAddressList {
            background: url("../assets/img/noStStore.png") no-repeat;
            background-size: 100%;
            width: 10rem;
            height: 10rem;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -5rem;
            margin-top: -5rem;
            text-align: center;
            padding-top: 11rem;
        }
    }
</style>
